var User = require("./../../CClass/class/User");
var gameDao = require("./gameDao");
var sever = require("./sever");
var schedule = require("node-schedule");
var log = require("./../../util/loginfo").getInstand;
var redis_send_and_listen = require("./../../util/redis_send_and_listen");

var roommgr = require("./roommgr");
var usermgr = require("./usermgr");
var mgr_dzpk = require("./gamemgr_dzpk");

var GameInfo = function () {

    var _gameinfo = "";

    var Game = function () {

        //初始化游戏
        this.init = function (_config) {
            log.info('####init game!####')
            gameConfig = _config;
            this.serverId = gameConfig.serverId;
            //初始化用户列表
            this.userList = {};
            //创建桌子 0位保存桌子状态
            this.tableList = new Array(gameConfig.tableMax);
            //创建座位
            for (var i = 0; i < this.tableList.length; ++i) {
                this.tableList[i] = new Array(gameConfig.seatMax + 1);
                this.initTable(i);
            }

            //在线人数为0
            this.onlinePlayerCount = 0;

            //维护模式
            this.maintain = false;
            this._io = {};
            this.GameList = new Array();

            this.lineOutList = {};
            this.line_out_dict = {};
            this.score_changeLogList = [];
            var self = this;
            this.matchId = 0;

            //获得比赛最大ID
            gameDao.getMatchId(gameConfig.serverId, function (_maxId) {
                self.matchId = _maxId + 1;
            })

            this.sever = new sever();
            var rule = new schedule.RecurrenceRule();
            var times = [];
            for (var i = 0; i < 60; i++) {
                times.push(i);
            }
            rule.second = times;
            var self = this;
            var j = schedule.scheduleJob(rule, function () {

                var nowDate = new Date();
                var minute = nowDate.getMinutes();
                var second = nowDate.getSeconds();

                if (second == 0) {
                    redis_send_and_listen.send_msg("OnlineUserMsg",{server_id:gameConfig.serverId,online_num:self.onlinePlayerCount});
                    //log.info("推送在线人数");
                }

                if (gameConfig.maintain) {
                    --gameConfig.maintainTime;
                    //log.info(gameConfig.maintainTime);
                    if (!gameConfig.maintainTime) {
                        self.disconnectAllUser();
                    }
                }
                self.score_changeLog();

                for(var sl in self.line_out_dict){
                    var l_o_d=self.line_out_dict[sl]
                    l_o_d.miao_shu--;
                    if(l_o_d.miao_shu<=0){
                        usermgr.exitRoom(sl);
                        // mgr_dzpk.delgameSeatsOfUsers(sl)
                        delete self.line_out_dict[sl];
                        self.lineOutSet({state: 0, userId: sl});
                        var u_socket = usermgr.get(sl);
                        u_socket.disconnect(1);

                    }
                }



            });
        }

        /**
         * 初始化桌子信息
         */
        this.initTable = function (tableId) {
            var tableObj = this.tableList[tableId];
            //初始化玩家信息
            tableObj[gameConfig.seatMax] = {seatId: -1, bet: -1, userId: -1, play: 1, win: -1};
            tableObj[gameConfig.seatMax].cardList = new Array(gameConfig.seatMax);

            var roomInfo = {
                id: tableId,
                onlineCount: 0,
                seats: [],
                scene: {
                    consume_num: gameConfig.bet,
                    limit_num: gameConfig.bet,
                },
                users: [],
                userDatas: {},
                waitingUsers: [],
                noMoneyArr: [],
                isWaiting: true, //房间是否挂起
                consume_type: 1,//金币场
                num: 10,
            };

            roomInfo.gameMgr = require("./gamemgr_dzpk.js");
            roomInfo.gameInfo = this;

            for (var i = 0; i < gameConfig.seatMax; ++i) {
                tableObj[gameConfig.seatMax].cardList[i] = [];
                roomInfo.seats.push({
                    userId: 0,
                    score: 0,
                    name: "",
                    ready: false,
                    seatIndex: i
                });
            }
            tableObj[gameConfig.seatMax].showList = [];
            for (var i = 0; i < tableObj.length - 1; ++i) {
                tableObj[i] = {};
                tableObj[gameConfig.seatMax].showList[i] = -1;
            }
            roommgr.createRoom(tableId, roomInfo);
        }

        this.setIo = function (_io, _Csocket) {
            this.sever.setIo(_io, _Csocket);
            this._io = _io;
            this._Csocket = _Csocket;
        }

        this.exitRoom = function (_socket) {
            this.sever.LogoutRoom(this.userList[_socket.userId], _socket);
            delete this.userList[_socket.userId];
            this.onlinePlayerCount--;
        }

        //判断是否是同一scoket连续登录，不允许
        this.isLoginAgain = function (socket) {
            if (socket.userId) {
                return this.userList[socket.userId].Islogin();
            } else {
                return false;
            }
        }

        //添加用户
        this.addUser = function (_userInfo, socket) {
            this.userList[_userInfo.userid] = new User(_userInfo, socket);
        }

        /**
         * 更新用户
         */
        this.updateUser = function (userInfo) {
            if (!this.userList[userInfo._userId]) return;

            //已经断线
            if (this.userList[userInfo._userId]._isLeave) {
                var result = {ResultCode: 0, userId: userInfo._userId};
                this._Csocket.emit("userDisconnect", result);
                delete this.userList[userInfo._userId];
                log.info("updateUser userid " + userInfo._userId + " socket disconnect!!!!!!!!!");
                return;
            }
            log.info("登录服务器传来userId:" + userInfo._userId + " score:" + userInfo._score);
            this.userList[userInfo._userId].update(userInfo);
            log.info("更新后userId:" + this.userList[userInfo._userId]._userId + " score:" + this.userList[userInfo._userId]._score);

            this.LoginGame(userInfo._userId, this.serverId);
            this.onlinePlayerCount++;

            var socketItem = this.userList[userInfo._userId]._socket;
            var resultObj = {
                account: this.userList[userInfo._userId]._account,
                id: this.userList[userInfo._userId]._userId,
                nickname: this.userList[userInfo._userId]._nickname,
                score: this.userList[userInfo._userId]._score
            };
            result = {resultid: 1, msg: 'login ' + gameConfig.gameName + ' succeed!', Obj: resultObj};
            socketItem.emit('loginGameResult', result);
        }

        //获得在线人数
        this.getOnlinePlayerCount = function () {
            return this.onlinePlayerCount;
        }

        //在线所有人
        this.getOnlinePlayer = function () {
            return this.userList;
        }

        this.score_changeLog = function () {
            var saveListTemp = [];
            var ItemTemp;
            var max = 0;
            if (this.score_changeLogList.length > 200) {
                max = 200;
            } else {
                max = this.score_changeLogList.length;
            }
            for (var i = 0; i < max; i++) {
                if (this.score_changeLogList.length > 0) {
                    ItemTemp = this.score_changeLogList.shift();
                    saveListTemp.push(ItemTemp);
                }
            }
            if (saveListTemp.length > 0) {
                this._Csocket.emit("score_changeLog", saveListTemp);
            }
        }

        //删除用户
        this.deleteUser = function (_socket,is_exit) {
            log.info("deleteUser")
            if (_socket.userId && this.userList[_socket.userId]) {
                //判断是否还有牌局在继续
                var tableId = this.userList[_socket.userId].getTable();
                if (tableId >= 0) {
                    //判断自己是否在游戏当中
                    var onlineP = false;
                    var roomInfo = roommgr.getRoom(tableId);
                    var waitingUsers=roomInfo.waitingUsers;
                    var qipailist= roomInfo.qipailist;
                    var is_waitingUsers=false;
                    var is_qipai=false;

                    if(waitingUsers){
                        for(var rwu in waitingUsers){
                            if(waitingUsers[rwu].userid==_socket.userId){
                                is_waitingUsers=true;
                                break
                            }
                        }
                    }
                    if(qipailist){
                        if(qipailist.indexOf(_socket.userId)>-1){
                            is_qipai=true
                        }
                    }

                    // log.info("deleteUser---------------------------------------")
                    // log.info(roomInfo.is_start);
                    // log.info(is_waitingUsers);
                    // log.info(is_qipai);
                    // log.info(qipailist);


                    if (roomInfo.is_start && !is_waitingUsers && !is_qipai) {
                        onlineP = true
                    }
                    if(is_exit=="transport close"){
                        onlineP = true
                    }
                    log.info("onlineP-----------------------")
                    log.info(is_exit)
                    log.info(onlineP)

                    var tablestring = "table" + tableId;
                    _socket.leave(tablestring);

                    if (onlineP) {
                        //当前局有下注
                        this.sever.lineOut(this.userList[_socket.userId], _socket);
                        //通知登录服务器
                        this.lineOutSet({
                            state: 1,
                            userId: _socket.userId,
                            tableId: this.userList[_socket.userId].getTable(),
                            seatId: this.userList[_socket.userId].getSeat()
                        });
                        log.info("用户" + this.userList[_socket.userId]._userId + "断线");
                        this._Csocket.emit("lineOut", {
                            signCode: gameConfig.LoginServeSign,
                            state: 1,
                            gameId: gameConfig.gameId,
                            serverId: gameConfig.serverId,
                            userId: _socket.userId,
                            tableId: tableId,
                            seatId: this.userList[_socket.userId].getSeat(),
                        })
                        delete this.userList[_socket.userId];
                    } else {
                        log.info("退出")
                        usermgr.exitRoom(_socket.userId);
                        var tableId = this.userList[_socket.userId].getTable();
                        //发送信息给其他人
                        var tablestring = "table" + tableId;
                        _socket.broadcast.to(tablestring).emit('PlayerOut', {
                            PlayerSeatId: this.userList[_socket.userId].getSeat(),
                            userId: _socket.userId
                        });
                        this._Csocket.emit("lineOut", {
                            signCode: gameConfig.LoginServeSign,
                            state: 0,
                            gameId: gameConfig.gameId,
                            serverId: gameConfig.serverId,
                            userId: _socket.userId,
                            tableId: tableId,
                            seatId: this.userList[_socket.userId].getSeat()
                        })
                        log.info("用户离开!userid:" + this.userList[_socket.userId]._userId
                            + " Account:" + this.userList[_socket.userId]._account
                            + " score:" + this.userList[_socket.userId]._score);
                        this.sever.LogoutRoom(this.userList[_socket.userId], _socket);
                        delete this.userList[_socket.userId];
                        --this.onlinePlayerCount;
                    }
                } else {
                    log.info("用户没有登录桌子离开!:" + this.userList[_socket.userId]._userId);
                    delete this.userList[_socket.userId];
                    --this.onlinePlayerCount;
                }
            }
        }

        //删除用户
        this.deleteUserById = function (_userId, msg) {
            if (_userId) {
                var socketItem = this.userList[_userId]._socket;
                result = {resultid: 0, msg: msg};
                socketItem.emit('loginGameResult', result);
                socketItem.userId = null;
                delete this.userList[_userId];
            }
        }

        //获得用户当前分数
        this.getUserscore = function (_userId) {
            if (_userId) {
                return this.userList[_userId]._score;
            }
        }

        //获得用户
        this.getUser = function (_userId) {
            if (_userId) {
                return this.userList[_userId];
            }
        }

        //用户是否在线
        this.IsPlayerOnline = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.info("查询在线,参数错误");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                //log.info("查询在线,未找到" + _userId + "用户");
                return 1;
            } else {
                return 0;
            }
        }

        //获得用户当前分数
        this.getPlayerScore = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.info("查询分数,参数错误");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                //log.info("查询在线,未找到" + _userId + "用户");
                return this.userList[_userId].getScore();
            } else {
                return -1;
            }
        }

        //GM加分
        this.addgold = function (_userId, score) {
            if (!_userId) {					//传输ID错误
                log.info("加分,未登录")
                return 0;
            }
            if (!this.userList[_userId]) {	//未找到用户
                log.info("加分,未登录")
                return 0
            } else {
                log.info(score)
                if (this.userList[_userId].addgold(score)) {
                    log.info(this.userList[_userId].getScore())
                    log.info("加分成功!")
                    var tablestring = "table" + this.userList[_userId].getTable();
                    log.info('德州扑克使用金币==============用户:' + _userId + "，使用金币:" + score);
                    this._io.sockets.in(tablestring).emit('addgoldResult', {
                        userId: _userId,
                        userSeatId: this.userList[_userId].getSeat(),
                        userScore: this.userList[_userId]._score
                    })
                    return 1;
                } else {
                    log.info("减分失败,大于用户分数!");
                    return 0;
                }
            }
        }

        this.GameBalance = function (userItem, userWin) {
            log.info("GameBalance")
            //判断玩家是否在线
            if (this.userList[userItem]) {
                // log.info("用户金币:-------",this.userList[userItem]._score)
                var youScore = this.userList[userItem].getScore();
                this.userList[userItem].winscore(userWin);
                var youNowScore = this.userList[userItem].getScore();
                //记录金钱变化量
                var userInfolog = {
                    userid: userItem,
                    score_before: youScore,
                    score_change: userWin,
                    score_current: youNowScore,
                    change_type: gameConfig.logflag,
                    isOnline: true
                };
                this.score_changeLogList.push(userInfolog);

                // log.info("用户金币:-------",this.userList[userItem]._score)


            } else {
                this._Csocket.emit("GameBalance", {
                    signCode: gameConfig.LoginServeSign,
                    sendUserId: userItem,
                    sendCoin: userWin,
                    change_type: gameConfig.logflag
                })
            }
        }

        //进入游戏
        this.LoginGame = function (_userId, gametype) {
            if (!this.userList[_userId]) return;
            this.userList[_userId].loginGame(gametype);
        }


        //是否允许进入游戏
        this.ApplyLogin = function (_socket, _userId) {
            //发奖时间,并自己参与了下注***
            var linemsg = this.getLineOutMsg(_userId);
            if (!this.sever.ApplyLogin() && linemsg.Result) {
                _socket.emit("LoginRoomResult", {ResultCode: 0, msg: "正在发奖,稍后进入!"})
                return false;
            } else {
                return true;
            }
        }

        //进入房间
        this.LoginRoom = function (_userId, roomid, _socket) {
            if (!this.userList[_userId]) return;

            delete this.line_out_dict[_userId]


            if (!this.userList[_userId].getGameId()) {
                log.info("用户" + _userId + ",没有进入任何游戏,进入房间")
                return;
            }

            if (this.userList[_userId].getSeat() != -1) {
                log.info("用户" + _userId + "已经有座位");
                return;
            }

            this.userList[_userId].loginRoom(roomid);
            var LoginResult;
            var linemsg = this.getLineOutMsg(_userId);
            var is_duanxian= 1;
            if (linemsg.Result) {
                log.info("断线重连接table:" + linemsg.tableId + " seatid:" + linemsg.seatId);
                LoginResult = this.sever.LoginRoombyLineOut(this.getUser(_userId), _socket, linemsg.tableId, linemsg.seatId);
                this.lineOutSet({state: 0, userId: _userId});
                is_duanxian= 2
            } else {
                LoginResult = this.sever.LoginRoom(this.getUser(_userId), _socket,this.userList);
            }


            //进入房间自动准备


            //进入房间后，帮分配座位
            var ResultData = {tableId: LoginResult.tableId, seatId: LoginResult.seatId}
            _socket.emit("LoginRoomResult", {ResultCode: 1, ResultData: ResultData});

            if (true) {
                var tablestring = "table" + LoginResult.tableId;
                _socket.join(tablestring);

                var url = 0;

                var userData = {
                    userId: this.userList[_userId]._userId,
                    nickname: this.userList[_userId]._nickname,
                    headimgurl: this.userList[_userId]._headimgurl,
                    score: this.userList[_userId]._score,
                    seatId: LoginResult.seatId,
                    userType: this.userList[_userId]._Robot,
                    init_score: gameConfig.autoOut
                };

                log.info('查看用户数据======' + JSON.stringify(userData));

                roommgr.enterRoom(LoginResult.tableId, userData, function (ret) {

                    //检查房间合法性
                    var userId = _socket.userId;
                    var roomId = roommgr.getUserRoom(userId);
                    usermgr.bind(userId, _socket);
                    //返回房间信息
                    var roomInfo = roommgr.getRoom(roomId);
                    var userData = null;
                    var seats = [];
                    for (var i = 0; i < roomInfo.seats.length; ++i) {
                        var rs = roomInfo.seats[i];
                        var online = false;
                        if (rs.userId > 0) {
                            online = usermgr.isOnline(rs.userId);
                        }
                        seats.push({
                            userid: rs.userId,
                            ip: rs.ip,
                            score: rs.score,
                            name: rs.name,
                            online: online,
                            ready: rs.ready,
                            seatindex: i,
                            headimgurl: rs.headimgurl,
                        });
                        if (userId == rs.userId) {
                            userData = seats[i];
                        }
                    }
                    //通知前端
                    var result = {
                        errcode: 0,
                        errmsg: "ok",
                        data: {
                            roomid: roomInfo.id,
                            conf: roomInfo.conf,
                            numofgames: roomInfo.numOfGames,
                            scene: roomInfo.scene,
                            seats: seats,
                        },
                        ret:is_duanxian
                    };
                    log.info('玩家进入房间:' + JSON.stringify(result));
                    _socket.gameMgr = roomInfo.gameMgr;
                    _socket.gameInfo = roomInfo.gameInfo;
                    roommgr.addOnlineCount(roomId); //在线玩家+1
                    // log.info("result----------------------------------------")
                    // log.info(JSON.stringify(result.data.seats))
                    _socket.emit('login_result', result);
                    usermgr.broacastInRoom('new_user_comes_push', userData, userId, true);

                })
                // _socket.broadcast.to(tablestring).emit('playEnter', {
                //     ResultCode: 1,
                //     ResultData: {
                //         userId: _userId,
                //         tableId: LoginResult.tableId,
                //         seatId: LoginResult.seatId,
                //         nickname: this.userList[_userId]._nickname,
                //         score: this.userList[_userId]._score,
                //         headimgurl: url,
                //         userType: this.userList[_userId]._Robot
                //     }
                // });
            }


            log.info("登录进来桌子id:" + LoginResult.tableId);
            log.info("登录进来座位id:" + LoginResult.seatId);
        }

        //断线保存
        this.lineOutSet = function (_info) {
            if (_info.state == 1) {
                //添加
                this.lineOutList[_info.userId] = {tableId: _info.tableId, seatId: _info.seatId}
            } else {
                //移除
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: _info.userId
                })
                //移除
                delete this.lineOutList[_info.userId];
            }
        }

        //获得断线用户信息
        this.getLineOutMsg = function (_userId) {
            if (this.lineOutList[_userId]) {
                this.lineOutList[_userId].Result = 1;
                return this.lineOutList[_userId];
            } else {
                return {Result: 0};
            }
        }

        //清楚断线用户信息
        this.cleanLineOut = function () {
            //清理登录服务器
            //log.info(this.lineOutList)
            for (var Item in this.lineOutList) {

                Item = parseInt(Item)
                var tableId = this.lineOutList[Item].tableId;
                var tablestring = "table" + tableId;
                this._io.sockets.in(tablestring).emit('PlayerOut', {
                    PlayerSeatId: this.lineOutList[Item].seatId,
                    userId: Item
                });
                this.sever.cleanLineOut(tableId, this.lineOutList[Item].seatId)
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: Item
                })
            }
            this.lineOutList = {};
        }


        //清楚断线桌子断线用户
        this.cleanLineOutByTable = function (_tableId) {
            //清理登录服务器
            log.info("清理掉线")
            for (var Item in this.lineOutList) {
                Item = parseInt(Item);
                var tableId = this.lineOutList[Item].tableId;
                if (_tableId == tableId) {
                    var tablestring = "table" + tableId;
                    this._io.sockets.in(tablestring).emit('PlayerOut', {
                        PlayerSeatId: this.lineOutList[Item].seatId,
                        userId: Item
                    });
                    this.sever.cleanLineOut(tableId, this.lineOutList[Item].seatId)
                    this._Csocket.emit("lineOut", {
                        signCode: gameConfig.LoginServeSign,
                        state: 0,
                        gameId: gameConfig.gameId,
                        userId: Item
                    });
                    delete this.lineOutList[Item];
                }
            }
        }
        this.sendTalbeMsg = function (tablestring,key,data) {
            //发送消息
            log.info("桌子发送消息")
            // log.info(this._io.sockets.in(tablestring))
            this._io.sockets.in(tablestring).emit(key, data)
        }



        /**
         * 踢出全部用户
         */
        this.disconnectAllUser = function () {
            for (var itme in this.userList) {
                this.userList[itme]._socket.disconnect();
            }
            log.info("服务器开启维护，已经全部离线");
        }

        //设置维护状态
        this.Setmaintain = function () {
            gameConfig.maintain = true;
        }

        //是否维护
        this.isMaintain = function () {
            return gameConfig.maintain;
        }


    }


    if (_gameinfo) {
        return {getInstand: _gameinfo}
    } else {
        log.info("####创建游戏!####");
        _gameinfo = new Game();
        return {getInstand: _gameinfo}
    }

}()


module.exports = GameInfo;

